<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Trophy,
  Search,
  Plus,
  Edit,
  Delete,
  User,
  Medal
} from '@element-plus/icons-vue'
import request from '@/utils/request'

// 接口定义
interface Channel {
  id: string
  name: string
  avatarUrl?: string
  owner?: {
    id: string
    loginId: string
    nickname?: string
  }
}

interface Ranking {
  id: string
  channelId: string
  period: string
  rankPosition: number
  viewCount: number
  giftCount: number
  watchSeconds: number
  score: number
  isManual: boolean
  createdAt: string
  updatedAt: string
  channel: Channel
}

// 响应式数据
const loading = ref(false)
const rankings = ref<Ranking[]>([])
const channels = ref<Channel[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const selectedPeriod = ref('all')

// 对话框状态
const showCreateDialog = ref(false)
const editing = ref(false)
const saving = ref(false)
const channelLoading = ref(false)
let currentId: string | null = null

// 表单数据
const form = ref({
  channelId: '',
  period: 'all',
  rankPosition: 1,
  viewCount: 0,
  giftCount: 0,
  watchSeconds: 0,
  score: 0
})

// API基础URL
const API_BASE_URL = (import.meta as any)?.env?.VITE_API_BASE_URL || ''

// 计算属性
const hasRankings = computed(() => rankings.value.length > 0)

// 获取랭킹 목록
const fetchRankings = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      period: selectedPeriod.value
    }

    const response = await request.get('/api/admin/rankings', { params })
    rankings.value = response.data.rankings || []
    total.value = response.data.total || 0
  } catch (error) {
    console.error('랭킹 목록 가져오기 실패:', error)
    ElMessage.error('랭킹 목록을 가져오는데 실패했습니다')
  } finally {
    loading.value = false
  }
}

// 获取채널列表
const fetchChannels = async () => {
  if (channelLoading.value) return

  channelLoading.value = true
  try {
    const response = await request.get('/api/admin/channels', { params: { limit: 200 } })
    channels.value = response.data.channels || []
  } catch (error) {
    console.error('채널 목록 가져오기 실패:', error)
    ElMessage.error('채널 목록을 가져오는데 실패했습니다')
  } finally {
    channelLoading.value = false
  }
}

// 기간 변화处理
const handlePeriodChange = () => {
  currentPage.value = 1
  fetchRankings()
}

// 打开创建对话框
const openCreate = () => {
  editing.value = false
  currentId = null
  form.value = {
    channelId: '',
    period: selectedPeriod.value,
    rankPosition: 1,
    viewCount: 0,
    giftCount: 0,
    watchSeconds: 0,
    score: 0
  }

  // 确保有채널数据
  if (channels.value.length === 0) {
    fetchChannels()
  }
  showCreateDialog.value = true
}

// 打开编辑对话框
const openEdit = (ranking: Ranking) => {
  editing.value = true
  currentId = ranking.id
  form.value = {
    channelId: ranking.channelId,
    period: ranking.period,
    rankPosition: ranking.rankPosition,
    viewCount: ranking.viewCount,
    giftCount: ranking.giftCount,
    watchSeconds: ranking.watchSeconds,
    score: ranking.score
  }

  // 确保有채널数据
  if (channels.value.length === 0) {
    fetchChannels()
  } else {
    // 确保当前채널在选项中
    const currentChannel = channels.value.find(c => c.id === ranking.channelId)
    if (!currentChannel) {
      channels.value.push(ranking.channel)
    }
  }
  showCreateDialog.value = true
}

// 保存랭킹
const save = async () => {
  if (!form.value.channelId) {
    ElMessage.error('채널을 선택해주세요')
    return
  }

  saving.value = true
  try {
    if (editing.value && currentId) {
      await request.put(`/api/admin/rankings/${currentId}`, form.value)
      ElMessage.success('랭킹 수정 성공')
    } else {
      await request.post('/api/admin/rankings', form.value)
      ElMessage.success('랭킹 생성 성공')
    }
    showCreateDialog.value = false
    fetchRankings()
  } catch (error) {
    console.error('랭킹 저장 실패:', error)
    ElMessage.error(editing.value ? '랭킹 수정 실패' : '랭킹 생성 실패')
  } finally {
    saving.value = false
  }
}

// 删除랭킹
const deleteRanking = async (ranking: Ranking) => {
  try {
    await ElMessageBox.confirm(
      '이 랭킹을 삭제하시겠습니까?',
      '삭제 확인',
      {
        confirmButtonText: '삭제',
        cancelButtonText: '취소',
        type: 'warning'
      }
    )

    ranking.deleting = true
    await request.delete(`/api/admin/rankings/${ranking.id}`)
    ElMessage.success('랭킹 삭제 성공')
    fetchRankings()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('랭킹 삭제 실패:', error)
      ElMessage.error('랭킹 삭제 실패')
    }
  } finally {
    ranking.deleting = false
  }
}

// 页面变化处理
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchRankings()
}

// 기간 문본
const getPeriodText = (period: string) => {
  switch (period) {
    case 'all': return '전체'
    case 'daily': return '일간'
    case 'weekly': return '주간'
    case 'monthly': return '월간'
    default: return '알 수 없음'
  }
}

// 유형 문본
const getTypeText = (isManual: boolean) => {
  return isManual ? '수동' : '자동'
}

// 유형 类型
const getTypeType = (isManual: boolean) => {
  return isManual ? 'success' : 'info'
}

// 格式化数字
const formatNumber = (num: number) => {
  return num.toLocaleString()
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('ko-KR')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchRankings()
  fetchChannels()
})
</script>

<template>
  <div class="mobile-ranking-management">
    <!-- 기간 필터 -->
    <div class="mobile-filter-section">
      <el-select
        v-model="selectedPeriod"
        @change="handlePeriodChange"
        style="width: 100%"
        size="large"
      >
        <el-option label="전체" value="all" />
        <el-option label="일간" value="daily" />
        <el-option label="주간" value="weekly" />
        <el-option label="월간" value="monthly" />
      </el-select>
    </div>

    <!-- 操作按钮 -->
    <div class="mobile-action-section">
      <el-button type="primary" :icon="Plus" @click="openCreate" size="large" style="width: 100%;">
        새 랭킹 추가
      </el-button>
    </div>

    <!-- 랭킹 列表 -->
    <div class="mobile-rankings-list" v-loading="loading">
      <!-- 空状态 -->
      <div v-if="!hasRankings && !loading" class="mobile-empty">
        <el-icon class="mobile-empty-icon" size="48">
          <Trophy />
        </el-icon>
        <div class="mobile-empty-text">랭킹이 없습니다</div>
        <el-button type="primary" :icon="Plus" @click="openCreate" style="margin-top: 16px;">
          첫 번째 랭킹 추가
        </el-button>
      </div>

      <!-- 랭킹 卡片列表 -->
      <div v-else class="ranking-cards">
        <div v-for="ranking in rankings" :key="ranking.id" class="mobile-ranking-card">
          <!-- 랭킹 头部信息 -->
          <div class="ranking-header">
            <div class="ranking-position">
              <el-icon class="position-icon" size="24">
                <Medal />
              </el-icon>
              <span class="position-number">{{ ranking.rankPosition }}</span>
            </div>
            <div class="channel-info">
              <div class="channel-avatar">
                <img
                  v-if="ranking.channel.avatarUrl"
                  :src="`${API_BASE_URL}${ranking.channel.avatarUrl}`"
                  alt="채널 아바타"
                  class="avatar-image"
                />
                <el-icon v-else class="avatar-placeholder" size="24">
                  <User />
                </el-icon>
              </div>
              <div class="channel-details">
                <div class="channel-name">{{ ranking.channel.name }}</div>
                <div class="owner-info" v-if="ranking.channel.owner">
                  {{ ranking.channel.owner.nickname || ranking.channel.owner.loginId }}
                </div>
              </div>
            </div>
            <div class="ranking-meta">
              <el-tag :type="getTypeType(ranking.isManual)" size="small">
                {{ getTypeText(ranking.isManual) }}
              </el-tag>
              <el-tag type="info" size="small">
                {{ getPeriodText(ranking.period) }}
              </el-tag>
            </div>
          </div>

          <!-- 랭킹 统计信息 -->
          <div class="ranking-stats">
            <div class="stat-item">
              <span class="stat-label">시청자 수:</span>
              <span class="stat-value">{{ formatNumber(ranking.viewCount) }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">선물 수량:</span>
              <span class="stat-value">{{ formatNumber(ranking.giftCount) }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">시청 시간:</span>
              <span class="stat-value">{{ formatNumber(ranking.watchSeconds) }}초</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">점수:</span>
              <span class="stat-value score">{{ ranking.score }}</span>
            </div>
          </div>

          <!-- 랭킹 详细信息 -->
          <div class="ranking-details">
            <div class="detail-item">
              <span class="detail-label">업데이트 시간:</span>
              <span class="detail-value">{{ formatDate(ranking.updatedAt) }}</span>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="ranking-actions">
            <el-button
              :icon="Edit"
              size="small"
              @click="openEdit(ranking)"
              :disabled="ranking.deleting"
            >
              편집
            </el-button>
            <el-button
              :icon="Delete"
              size="small"
              type="danger"
              @click="deleteRanking(ranking)"
              :loading="ranking.deleting"
            >
              삭제
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="total > pageSize" class="mobile-pagination">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
        @current-change="handlePageChange"
        small
      />
    </div>

    <!-- 创建/编辑 랭킹 对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editing ? '랭킹 편집' : '랭킹 추가'"
      width="95%"
      :close-on-click-modal="false"
      class="mobile-dialog"
    >
      <el-form :model="form" label-position="top" class="mobile-form">
        <el-form-item label="채널 선택" required>
          <el-select
            v-model="form.channelId"
            placeholder="채널을 선택하세요"
            style="width: 100%"
            filterable
            :loading="channelLoading"
          >
            <el-option
              v-for="channel in channels"
              :key="channel.id"
              :label="channel.name"
              :value="channel.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="기간" required>
          <el-select v-model="form.period" style="width: 100%">
            <el-option label="전체" value="all" />
            <el-option label="일간" value="daily" />
            <el-option label="주간" value="weekly" />
            <el-option label="월간" value="monthly" />
          </el-select>
        </el-form-item>

        <el-form-item label="순위 위치" required>
          <el-input-number
            v-model="form.rankPosition"
            :min="1"
            :max="999"
            style="width: 100%"
            placeholder="순위 위치를 입력하세요"
          />
        </el-form-item>

        <el-form-item label="시청자 수">
          <el-input-number
            v-model="form.viewCount"
            :min="0"
            :max="999999999"
            style="width: 100%"
            placeholder="시청자 수를 입력하세요"
          />
        </el-form-item>

        <el-form-item label="선물 수량">
          <el-input-number
            v-model="form.giftCount"
            :min="0"
            :max="999999999"
            style="width: 100%"
            placeholder="선물 수량을 입력하세요"
          />
        </el-form-item>

        <el-form-item label="시청 시간">
          <el-input-number
            v-model="form.watchSeconds"
            :min="0"
            :max="999999999"
            style="width: 100%"
            placeholder="시청 시간을 입력하세요"
          />
          <div class="form-tip">단위: 초</div>
        </el-form-item>

        <el-form-item label="점수">
          <el-input-number
            v-model="form.score"
            :min="0"
            :max="999999999"
            style="width: 100%"
            placeholder="점수를 입력하세요"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="mobile-dialog-footer">
          <el-button @click="showCreateDialog = false" size="large">취소</el-button>
          <el-button
            type="primary"
            @click="save"
            :loading="saving"
            :disabled="!form.channelId"
            size="large"
          >
            {{ editing ? '수정' : '생성' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 移动端랭킹 관리主容器 */
.mobile-ranking-management {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 100%;
}

/* 기간 필터区域 */
.mobile-filter-section {
  background: var(--el-bg-color);
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

/* 操作按钮区域 */
.mobile-action-section {
  padding: 0 16px;
}

/* 랭킹 列表容器 */
.mobile-rankings-list {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

/* 空状态 */
.mobile-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: var(--el-text-color-placeholder);
  text-align: center;
}

.mobile-empty-icon {
  color: var(--el-color-warning);
  margin-bottom: 16px;
}

.mobile-empty-text {
  font-size: 16px;
  margin-bottom: 8px;
}

/* 랭킹 卡片容器 */
.ranking-cards {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 0 16px;
}

/* 移动端랭킹 卡片 */
.mobile-ranking-card {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.mobile-ranking-card:active {
  transform: scale(0.98);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

/* 랭킹 头部信息 */
.ranking-header {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 16px;
}

.ranking-position {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 60px;
}

.position-icon {
  color: var(--el-color-warning);
  margin-bottom: 4px;
}

.position-number {
  font-size: 18px;
  font-weight: 700;
  color: var(--el-color-warning);
}

.channel-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 0;
}

.channel-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  background: var(--el-fill-color-light);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  color: var(--el-text-color-placeholder);
}

.channel-details {
  flex: 1;
  min-width: 0;
}

.channel-name {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
  word-break: break-word;
}

.owner-info {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.ranking-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: flex-end;
}

/* 랭킹 统计信息 */
.ranking-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-bottom: 16px;
  padding: 12px;
  background: var(--el-fill-color-extra-light);
  border-radius: 8px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.stat-label {
  color: var(--el-text-color-regular);
  font-weight: 500;
}

.stat-value {
  color: var(--el-text-color-primary);
  font-weight: 600;
}

.stat-value.score {
  color: var(--el-color-primary);
  font-size: 16px;
}

/* 랭킹 详细信息 */
.ranking-details {
  margin-bottom: 16px;
  padding: 12px;
  background: var(--el-fill-color-extra-light);
  border-radius: 8px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.detail-label {
  color: var(--el-text-color-regular);
  font-weight: 500;
}

.detail-value {
  color: var(--el-text-color-primary);
  text-align: right;
}

/* 랭킹 操作按钮 */
.ranking-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.ranking-actions .el-button {
  min-width: 60px;
}

/* 分页 */
.mobile-pagination {
  display: flex;
  justify-content: center;
  padding: 16px;
  background: var(--el-bg-color);
  border-radius: 12px;
  margin: 0 16px;
}

/* 移动端对话框样式 */
.mobile-dialog {
  margin: 5vh auto;
}

.mobile-form {
  padding: 0;
}

.mobile-form .el-form-item {
  margin-bottom: 20px;
}

.mobile-form .el-form-item__label {
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
}

/* 表单提示 */
.form-tip {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  margin-top: 4px;
  line-height: 1.4;
}

/* 移动端对话框底部 */
.mobile-dialog-footer {
  display: flex;
  gap: 12px;
  padding: 16px 0 0 0;
}

.mobile-dialog-footer .el-button {
  flex: 1;
}

/* 暗黑模式适配 */
:root.dark .mobile-ranking-card {
  background: var(--el-bg-color);
  border-color: var(--el-border-color);
}

:root.dark .ranking-stats {
  background: var(--el-fill-color-darker);
}

:root.dark .ranking-details {
  background: var(--el-fill-color-darker);
}
</style>
